import React, { Component } from 'react';
import { Input, message, Popover, Switch, Table, Dropdown, Menu, Icon, Button } from 'antd';
import invoiceManagementService from '../invoice-management.service';
import { messages } from 'share/common';
import moment from 'moment';

const Search = Input.Search;

class InvoiceInspection extends Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: messages('supplier.key221')/*抬头（法人名称）*/, dataIndex: 'legalEntityName', render: value => {
            return <Popover placement="topLeft" content={value}>{ value || '-'}</Popover>;
          }
        },
        {
          title: messages('supplier.key222')/*纳税人识别号*/, dataIndex: 'taxpayerNumber', render: value => {
            return <Popover placement="topLeft" content={value}>{value ||'-'}</Popover>;
          }
        },
        {
          title: messages('supplier.key223')/*相关订单*/, dataIndex: 'orderCode', render: value => {
            return <Popover placement="topLeft" content={value}>{value ||'-'}</Popover>;
          }
        },
        {
          title: messages('supplier.key224')/*开通日期*/, dataIndex: 'effectiveDate', render: value => {
            return value ? moment(value).format('YYYY-MM-DD') : '-';
          }
        },
        {
          title: messages('supplier.key225')/*到期日期*/, dataIndex: 'expireDate', render: value => {
            return value ? moment(value).format('YYYY-MM-DD') : '-';
          }
        },
        {
          title: messages('supplier.key226')/*是否启用*/, dataIndex: 'status', render: (value, record) => {
            return (
              <div>
                <Switch
                  defaultChecked={value}
                  checked={value}
                  onChange={() => this.handleAssociatedOrders(value, record)}/>
                <span style={{ marginLeft: 10 }}>{value ? messages('common.status.enable')/*启用*/ : messages('common.status.disable')/*禁用*/}</span>
              </div>
            );
          }
        }
      ],
      pagination: {
        total: 0,
        page: 0,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      },
      loading: true,
      data: [],
      legalEntityName: '',
      serviceTypeCode: props.serviceTypeCode,
      selectedRowKeys: [],
      menus:{
        name:messages('supplier.key491')/*批量操作*/,
        dataSources: [
          {
            name: messages('supplier.key492')/*批量开启*/,
            key: 1
          },
          {
            name: messages('supplier.key493')/*批量关闭*/,
            key: 2
          }
        ]
      }
    };
  }

  componentWillMount() {
    this.handleGetLegalEntities();
  }

  componentWillReceiveProps = (props) => {
    const { serviceTypeCode } = props;
    this.setState({ serviceTypeCode }, this.handleGetLegalEntities());
  };

  /**
   * @desc 启用禁用服务
   **/
  handleAssociatedOrders = (value, record) => {
    this.setState({ loading: true });
    const { serviceTypeCode } = this.state;
    let params;
    value
      ? params = { id: record.id }
      : params = {
        legalEntityId: record.legalEntityId,
        serviceTypeCode
      };
    invoiceManagementService.designatedLegalEntities(params)
      .then(res => {
        this.handleGetLegalEntities();
      })
      .catch(err => {
        message.error(err.response.data.message || messages('common.error'));
        this.setState({ loading: false });
      });
  };

  /**
   * @desc 获取法人列表
   **/
  handleGetLegalEntities = () => {
    let { pagination, data, loading, legalEntityName, serviceTypeCode, selectedRowKeys } = this.state;
    const params = {
      page: pagination.page,
      size: pagination.pageSize,
      serviceTypeCode,
      legalEntityName
    };
    invoiceManagementService.getLegalEntities(params)
      .then((res) => {
        pagination.total = Number(res.headers['x-total-count']) || 0;
        pagination.current = pagination.page + 1;
        data = res.data;
        selectedRowKeys = []
      })
      .finally(() => {
        loading = false;
        this.setState({ pagination, data, loading, selectedRowKeys });
      });
  };

  handleSearch = (e) => {
    let { pagination, loading, legalEntityName } = this.state;
    pagination['total'] = 0;
    pagination['page'] = 0;
    loading = true;
    legalEntityName = e;
    this.setState({ pagination, loading, legalEntityName }, () => {
      this.handleGetLegalEntities();
    });
  };

  onChange = (_pagination) => {
    let { pagination, loading } = this.state;
    pagination.page = _pagination.current - 1;
    pagination.pageSize = _pagination.pageSize;
    loading = true;
    this.setState({
      pagination,
      loading
    }, () => {
      this.handleGetLegalEntities();
    });
  };

  handleMenuClick = (e) => {
    if (e.key === '1') {
      this.handleBatchLegal('batchOpenLegalEntity', false);
      return;
    }
    if (e.key === '2') {
      this.handleBatchLegal('batchCloseLegalEntity', false);
    }
  };

  onSelectChange = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };

  handleOpenAll = () => {
    this.handleBatchLegal('batchOpenLegalEntity',true);
  };

  handleCloseAll = () => {
    this.handleBatchLegal('batchCloseLegalEntity',true);
  };

  handleBatchLegal = (flag, isAll) => {
    const { serviceTypeCode, selectedRowKeys } = this.state;
    const all = isAll;
    const _batch = () => {
      invoiceManagementService[flag]({ serviceTypeCode, all, arr: selectedRowKeys })
        .then(res => {
          !!res && message.success(res.data.msg);
          this.handleGetLegalEntities();
        })
        .finally(() => {
          this.setState({ loading: true });
        });
    };
    this.setState({ loading: true }, _batch);
  };

  renderMenu = () => {
    const { menus, selectedRowKeys } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        {menus.dataSources.map(item =>
          <Menu.Item key={item.key}>
            {item.name}
          </Menu.Item>
        )}
      </Menu>
    );

    return (
      <section>
        <Dropdown.Button
          className="inspection-dropdown"
          type="primary"
          disabled={!selectedRowKeys.length}
          overlay={menu}>
          {menus.name}
        </Dropdown.Button>
        <Button
          className="inspection-button"
          type="primary"
          onClick={this.handleOpenAll}>
          {messages('supplier.key494')/*开启全部*/}
        </Button>
        <Button
          className="inspection-button"
          type="primary"
          onClick={this.handleCloseAll}>
          {messages('supplier.key495')/*关闭全部*/}
        </Button>
      </section>
  );
  };

  render() {
    const { columns, pagination, loading, data, selectedRowKeys} = this.state;
    const rowSelection = { selectedRowKeys, onChange: this.onSelectChange, };
    return (
      <div className="invoice-inspection">
        {this.renderMenu()}
        <div className="invoice-inspection-header">
          <div className="invoice-inspection-title"> {messages('senior-service-open.key32', { arg1: pagination.total })/*共搜索到 {arg1} 条数据*/}</div>
          <Search
            className="invoice-inspection-search"
            enterButton={messages('common.search')/*搜索*/}
            placeholder={messages('senior-service-open.key33')/*请输入法人名称*/}
            onSearch={this.handleSearch}/>
        </div>
        <Table
          bordered
          size={'middle'}
          rowKey={'legalEntityId'}
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          rowSelection={rowSelection}
          onChange={this.onChange}
        />
      </div>
    );
  }
}

InvoiceInspection.propTypes = {
  type: React.PropTypes.string // 类型
};

export default InvoiceInspection;
